import HomeContent from '@components/Apps/MatchScore/HomeContent';
import axios, { AxiosRequestConfig } from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
// import useUserStore from './storage';
// import Cookies from 'js-cookie'
// import {localStorage} from '@/utils/storage';

const post = function (url: string, params: any) {
	const query = {
		url: url,
		method: 'post',
		withCredentials: true,
		timeout: 30000,
		data: params,
		headers: {
			'Content-Type': 'application/json',
			'request-ajax': true,
			'token': '',
		}
	}
	return request(false, query)
}

const load = function (url: string, params: any) {
	const query = {
		url: HomeContent.Default.api + url,
		method: 'post',
		withCredentials: true,
		timeout: 30000,
		data: params,
		headers: {
			'Content-Type': 'application/json',
			'request-ajax': true,
		}
	}
	// console.log(query)
	return request(false, query)
}

const get = function (url: any, params: any) {
	const query = {
		url: url,
		method: 'get',
		withCredentials: true,
		timeout: 30000,
		params: params,
		headers: { 'request-ajax': true, 'token': 'Cookies.get(import.meta.env.VITE_APP_TOKEN_KEY)' }
	}
	return request(false, query)
}

const request = function (loading: any, query: any) {
	let loadingShow: any = {}
	if (loading) {
		loadingShow = ElLoading.service({
			lock: false,
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.5)'
		})
	}
	return axios.request(query)
		.then(res => {
			console.log('///////////', res);

			if (res.status === 200 && res.data.response == null) {
				ElMessage({
					message: res.data.message,
					type: 'error'
				});
			} else if (res.data.code === 400 || res.data.code === 401) {
				// useUserStore().removeLoginCookies()
				localStorage.clear();
				window.location.href = '/';
			} else if (res.data.code === 500) {
				return Promise.reject(res.data)
			} else if (res.data.code === 501) {
				return Promise.reject(res.data)
			} else if (res.data.code === 502) {
				// useUserStore().removeLoginCookies()
				localStorage.clear();
				window.location.href = '/';
				return Promise.reject(null)
			} else {
				return Promise.resolve(res.data)
			}
		})
		.catch(e => {
			if (e !== null) {
				ElMessage({
					message: e.message,
					type: 'error'
				});
				return Promise.reject(e.message)
			} else {
				return Promise.reject(null)
			}
		}).finally(() => {
			if (loading) {
				loadingShow.close()
			}
		})
}
export {
	post,
	get,
	load,
}



